package cn.rcth.base.serivce.impl;

import cn.rcth.base.constants.BaiseConstants;
import cn.rcth.base.domain.UserAddress;
import cn.rcth.base.mapper.UserAddressMapper;
import cn.rcth.base.serivce.IUserAddressSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserAddressSerivceImpl implements IUserAddressSerivce {


    @Autowired
    private UserAddressMapper userAddressMapper;

    /**
     * 保存用户地址信息
     *
     * @param userAddress
     */
    @Override
    public Map addUserAddress(UserAddress userAddress ) {
        Map map = new HashMap();
        //查询当前用户地址的条数
        int num = userAddressMapper.selectUserAddressNum(userAddress.getUserId());
        if (num <= BaiseConstants.FIFTY) {
            //查看是否将此地址设为默认
            if (userAddress.getStatus().equals(BaiseConstants.DEFAULT_ADDRESS)) {
                //将之前的默认地址修改为正常地址
                Long userIds = userAddress.getUserId();
                UserAddress userAddress1 = userAddressMapper.selectDefaultUserAddress(userIds);
                //判断
                if (userAddress1 != null) {
                    userAddress1.setStatus(BaiseConstants.ADDRESS);
                    userAddressMapper.updateByPrimaryKey(userAddress1);
                }
            }
            if (userAddress.getId() != null) {
                String address = userAddress.getAddress();

                userAddressMapper.updateByPrimaryKey(userAddress);
            } else {
                userAddressMapper.insert(userAddress);
            }
        }else{
            map.put("msg","您的地址太多了,删除几个再添加吧");
            return map;
        }
        map.put("msg","SUCCESSFUL");
        return map;
    }
    /**
     * 查询当前用户所有地址
     *
     * @param id 用户id
     * @return
     */
    @Override
    public List<UserAddress> UserAddressAll(Long id) {
        List<UserAddress> userAddresses = userAddressMapper.selectUser(id);
        List<UserAddress> userAddresses1 = new ArrayList<>();
        for (UserAddress userAddress : userAddresses) {
            String address = userAddress.getAddress();
        /*    String[] split = address.split(" ");
            userAddress.setAddress(split[0]+split[1]+split[2]);*/
            userAddresses1.add(userAddress);
        }
        return userAddresses1;
    }

    @Override
    public void deleteAddUserAddress(Long addUserAddressId) {
        userAddressMapper.deleteByPrimaryKey(addUserAddressId);
    }


    @Override
    public UserAddress selectAddUserAddress(Long addUserAddressId) {
        UserAddress userAddress = userAddressMapper.selectuserAddressById(addUserAddressId);
        String address = userAddress.getAddress();
        return userAddress;
    }
}
